﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using DotNET4Study.IOExt;
using Microsoft.Win32.SafeHandles;

namespace DotNET4Study
{
    public class FileWatcherStudy
    {
        public static void Execute()
        {
            Console.WriteLine("现在开始监控D:\\Temp");
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"D:\Temp";
            //watcher.Filter = "*.txt";
            watcher.IncludeSubdirectories = true;
            watcher.EnableRaisingEvents = true;
            watcher.Created += new FileSystemEventHandler(watcher_Created);
        }

        static void watcher_Created(object sender, FileSystemEventArgs e)
        {
            //每个要操作的文件使用单独线程进行控制。
            Thread t = new Thread(new ParameterizedThreadStart(OperateFile));
            t.Start(e.FullPath);
        }


        static void OperateFile(object fileFullNameObject)
        {
            string fileFullName = fileFullNameObject.ToString();
            Console.WriteLine(fileFullName);

            bool isBusy = true;
            while (isBusy)
            {
                isBusy = ConfirmIsBusy(fileFullName);
                if (isBusy == true)
                {
                    Thread.Sleep(500);
                }
            }

            try
            {
                File.Delete(fileFullName);
            }
            catch { }
        }


        static bool ConfirmIsBusy(string fileFullName)
        {
            bool isBusy = false;
            using (SafeFileHandle fileHandle = CreateFileWrapper.CreateFile(fileFullName,
                                                                  EFileAccess.GenericRead,
                                                                  EFileShare.Read,
                                                                  IntPtr.Zero,
                                                                  ECreationDisposition.OpenExisting,
                                                                  EFileAttributes.Readonly,
                                                                  IntPtr.Zero))
            {
                if (fileHandle.IsInvalid)
                {
                    isBusy = true;
                }
                else
                {
                    isBusy = false;
                }
            }

            return isBusy;
        }
    }
}
